package com.fancy.application.common.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.fancy.application.sys.org.entity.SysOrgPerson;
import com.fancy.application.sys.org.service.ISysOrgPersonService;
import com.fancy.application.sys.org.service.impl.SysOrgPersonServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.List;

/**
 * 当前用户信息
 */
public class UserUtil {

    private static final ISysOrgPersonService sysOrgPersonService = SpringBeanUtil.getBean("sysOrgPersonService", SysOrgPersonServiceImpl.class);
    /**
     * 获取当前用户
     * @return SysOrgPerson
     */
    public static SysOrgPerson getCurrentUser(){
        String token = (String) getSubject().getPrincipal();
        return sysOrgPersonService.getPersonByToken(token);
    }

    private static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 验证当前用户是否存在此角色
     */
    public static Boolean isPermitted(String permission){
        if(StrUtil.isEmpty(permission)) return false;
        return getSubject().isPermitted(permission);
    }

    /**
     * 验证当前用户是否存在此角色
     */
    public static Boolean isAdmin(){

        return StrUtil.equals(getCurrentUser().getFdLoginName(), "admin");
    }

    /**
     * 验证当前用户是否存在此角色
     */
    public static Boolean isAdmin(SysOrgPerson person){
        if(StrUtil.equals(person.getFdLoginName(),"admin")){
            return true;
        } else {
            List<String> resList = sysOrgPersonService.getResByUserId(person.getFdId());
            return CollectionUtil.contains(resList, "SYSTEM_ADMIN");
        }
    }


}
